<template>
  <div id="EquipmentBookingAuditPage">
    <div v-if="false" class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">申请筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">设备名称</span>
          <el-input
            class="item-input"
            v-model="queryObj.deviceName"
            placeholder="请输入设备名称"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">申请人</span>
          <el-input
            class="item-input"
            v-model="queryObj.userName"
            placeholder="请输入申请人名称"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">申请列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />

          <el-table-column label="预约人">
            <template #default="scope">
              <div>{{ scope.row?.applicantInfo.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column label="申请时间">
            <template #default="scope">
              <div>
                {{ formatDate(scope.row?.createdAt) || "--" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开始时间">
            <template #default="scope">
              <div>
                {{ formatDate(scope.row?.flowDetail.startTime) || "--" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="结束时间">
            <template #default="scope">
              <div>
                {{ formatDate(scope.row?.flowDetail.endTime) || "--" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="设备名称">
            <template #default="scope">
              <div class="equipment-name-wrapper">
                <img
                  :src="
                    (scope.row?.deviceDetail.photoList &&
                      scope.row?.deviceDetail.photoList[0]?.url) ||
                    require('@/assets/images/defaultDevice.png')
                  "
                  alt="设备图片"
                  class="equipment-photo"
                />
                <div class="equipment-info-wrapper">
                  <span class="equipment-name">
                    {{ scope.row?.deviceDetail.name }}
                  </span>

                  <span class="equipment-sn">
                    SN：{{ scope.row?.deviceDetail.code }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="设备类型">
            <template #default="scope">
              <div>{{ scope.row?.deviceDetail.typeInfo?.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column label="设备型号">
            <template #default="scope">
              <div>{{ scope.row?.deviceDetail.model || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column label="设备负责人">
            <template #default="scope">
              <div>
                {{ scope.row?.deviceDetail.chargeUserInfo?.name || "--" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <div class="table-btn" @click="openBookingAuditDialog(scope.row)">
                审批
              </div>
              <div
                v-if="false"
                class="table-btn"
                @click="auditProgressHandle(scope.row)"
              >
                查看审批进度
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.page"
        :total="pagination.totalElements"
        :page-size="pagination.size"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 查看审批进度 -->
    <el-dialog
      class="self-dialog"
      v-model="auditProgressDialogVisible"
      title="查看审批进度"
      width="50%"
    >
      <div class="audit-progress-container">
        <div class="progress-steps">
          <div
            v-for="(step, index) in auditProgress"
            :key="index"
            class="progress-step"
            :class="step.status"
          >
            <div class="step-indicator">
              <div class="step-circle"></div>
              <div
                class="step-line"
                v-if="index < auditProgress.length - 1"
              ></div>
            </div>
            <div class="step-content">
              <div class="step-title">{{ step.stageDescription }}</div>
              <div class="step-time" v-if="step.approvalTime">
                {{ formatDate(step.approvalTime) || "" }}
              </div>
              <div class="step-handler" v-if="step.statusDescription">
                {{ step.statusDescription }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 预约审批弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="bookingAuditDialogVisible"
      title="预约审批"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="apply-audit-container">
        <!-- 预约设备信息 -->
        <div class="apply-info-section">
          <div class="section-title">预约设备信息</div>
          <div class="apply-info-content">
            <div class="info-item">
              <span class="info-label">预约人：</span>
              <span class="info-value">{{
                currentBookingRow?.applicantInfo.name || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">预约设备：</span>
              <span class="info-value">{{
                currentBookingRow?.deviceDetail.name || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">设备编号：</span>
              <span class="info-value">{{
                currentBookingRow?.deviceDetail.code || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">设备型号：</span>
              <span class="info-value">{{
                currentBookingRow?.deviceDetail.model || "--"
              }}</span>
              <span
                class="detail-link"
                @click="openEquipmentDetail(currentBookingRow)"
                >详情</span
              >
            </div>
          </div>
        </div>
        <!-- 预约信息 -->
        <div class="apply-info-section">
          <div class="section-title">预约信息</div>
          <div class="apply-info-content">
            <div class="info-item">
              <span class="info-label">开始时间：</span>
              <span class="info-value">{{
                formatDate(currentBookingRow?.flowDetail.startTime) || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">开始时间：</span>
              <span class="info-value">{{
                formatDate(currentBookingRow?.flowDetail.endTime) || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">用途：</span>
              <span class="info-value">{{
                currentBookingRow?.flowDetail.purpose || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">使用位置：</span>
              <span class="info-value">{{
                currentBookingRow?.flowDetail.location || "--"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">使用时长：</span>
              <span class="info-value"
                >{{
                  currentBookingRow?.flowDetail.usageDurationDays || "--"
                }}（天）</span
              >
            </div>
            <div class="info-item">
              <span class="info-label">最大提前量：</span>
              <span class="info-value"
                >{{
                  currentBookingRow?.flowDetail.maxAdvanceDays || "--"
                }}（天）</span
              >
            </div>
            <div class="info-item">
              <span class="info-label">频次限制：</span>
              <span class="info-value"
                >{{
                  currentBookingRow?.flowDetail.frequencyLimit || "--"
                }}（次）</span
              >
            </div>
          </div>
        </div>

        <!-- 审批流程追踪 -->
        <div class="approval-process-section">
          <div class="section-title">审批流程追踪</div>
          <div class="process-steps">
            <div
              v-for="(step, index) in auditProgress"
              :key="index"
              class="process-step"
              :class="step.status"
            >
              <div class="step-circle"></div>
              <div
                class="step-line"
                v-if="index < auditProgress.length - 1"
              ></div>
              <div class="step-content">
                <div class="step-title">{{ step?.approverInfo?.name }}</div>
                <div class="step-time" v-if="step.approvalTime">
                  {{ formatDate(step.approvalTime) || "" }}
                </div>
                <div class="step-status" v-if="step.status">
                  {{ statusMap[step.status] || "--" }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 审批意见 -->
        <div class="approval-comment-section">
          <el-form
            ref="bookingApprovalFormRef"
            :model="bookingApprovalForm"
            :rules="bookingApprovalFormRule"
            label-width="100px"
            label-position="right"
          >
            <el-form-item label="审批结果" prop="reason">
              <el-select
                v-model="bookingApprovalForm.result"
                placeholder="请选择审批结果"
              >
                <el-option label="通过" value="APPROVED" />
                <el-option label="驳回" value="REJECTED" />
              </el-select>
            </el-form-item>
            <el-form-item label="审批意见" prop="reason">
              <el-input
                v-model="bookingApprovalForm.comment"
                placeholder="请输入审批意见"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bookingAuditDialogVisible = false">取消</el-button>
          <el-button
            type="danger"
            @click="submitBookingApproval"
            :loading="bookingApprovalLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { formatDate } from "@/assets/js/utils";
import { PaginationType } from "@/api/globalType";
import { AuditProgressType } from "@/api/service/deviceApplicant";
import { detailsAPI } from "@/api/service/approvalFlow";
import { submitAPI } from "@/api/service/approvalFlow";
import { getReservationByIdAPI } from "@/api/service/reservations";

const router = useRouter();
const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");

// 表格数据
const queryObj = ref({
  deviceName: "",
  userName: "",
});
const pagination = ref<PaginationType>({
  page: 1,
  size: 50,
  totalElements: 0,
  totalPages: 0,
});
const tableData = ref([]);
const originTableData = ref([]);
// API调用保护状态
const listApiLoading = ref(false);

function getEquipmentList() {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  detailsAPI({
    approverUserCode: userInfo.userCode || "",
    processType: "DEVICE_RESERVATION",
    page: pagination.value.page,
    size: pagination.value.size,
  })
    .then((_data: any) => {
      const data = _data;
      tableData.value = data.content;
      originTableData.value = JSON.parse(JSON.stringify(data.content));
      pagination.value.page = data.page;
      pagination.value.size = data.size;
      pagination.value.totalElements = data.totalElements;
      pagination.value.totalPages = data.totalPages;
    })
    .catch(() => {
      ElMessage.error("获取申请列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getEquipmentList();

const searchHandle = () => {
  tableData.value = originTableData.value.filter((item: any) => {
    // 设备名称条件检查
    const deviceNameMatch =
      !queryObj.value.deviceName ||
      (item.deviceDetail?.name &&
        item.deviceDetail.name.includes(queryObj.value.deviceName));

    // 用户名条件检查
    const userNameMatch =
      !queryObj.value.userName ||
      (item.applicantInfo?.name &&
        item.applicantInfo.name.includes(queryObj.value.userName));

    // 只有所有条件都满足才返回该项
    return deviceNameMatch && userNameMatch;
  });
};

const sizeChangeHandle = (size: number) => {
  pagination.value.size = size;
  pagination.value.page = 1;
  getEquipmentList();
};
const currentChangeHandle = (page: number) => {
  pagination.value.page = page;
  getEquipmentList();
};

// 查看审批进度
const auditProgressDialogVisible = ref(false);
const auditProgressLoading = ref(false);
const auditProgress = ref<AuditProgressType[]>([]);

// 查看审批进度
const statusMap = {
  IN_PROGRESS: "进行中",
  COMPLETED: "已完成",
  NOT_STARTED: "未开始",
};
function getAuditProgress(id: string) {
  auditProgressLoading.value = true;
  getReservationByIdAPI(id)
    .then((_data) => {
      const data = _data as any;
      auditProgress.value = data.approvalRecords || [];
      auditProgress.value.unshift({
        id: "",
        stage: "",
        approverInfo: {
          name: "提交申请",
        },
        status: "COMPLETED",
        statusDescription: "已完成",
        result: null,
        resultDescription: "",
        comment: "",
        approverCode: "",
        approverName: "",
        approvalTime: "",
        priority: 0,
      });

      const inProgress = data.approvalRecords.filter((item) => {
        return item.status === "IN_PROGRESS";
      });
      let isCompleted = inProgress.length === 0;
      if (isCompleted) {
        auditProgress.value.push({
          id: "",
          stage: "",
          approverInfo: {
            name: "审批完成",
          },
          status: "COMPLETED",
          statusDescription: "已完成",
          result: null,
          resultDescription: "",
          comment: "",
          approverCode: "",
          approverName: "",
          approvalTime: "",
          priority: 0,
        });
      } else {
        auditProgress.value.push({
          id: "",
          stage: "",
          approverInfo: {
            name: "审批完成",
          },
          status: "NOT_STARTED",
          statusDescription: "未开始",
          result: null,
          resultDescription: "",
          comment: "",
          approverCode: "",
          approverName: "",
          approvalTime: "",
          priority: 0,
        });
      }
    })
    .catch(() => {
      ElMessage.error("获取审核进度失败");
    })
    .finally(() => {
      auditProgressLoading.value = false;
    });
}

function auditProgressHandle(row: any) {
  auditProgressDialogVisible.value = true;
  getAuditProgress(row.flowId);
}

// 预约审批相关
const bookingAuditDialogVisible = ref(false);
const currentBookingRow = ref<any>(null);
const bookingApprovalLoading = ref(false);
const bookingApprovalForm = ref({
  id: "",
  approverUserCode: "",
  approvalRecordId: "",
  flowId: "",
  result: "",
  comment: "",
});
const bookingApprovalFormRule = ref({
  result: [{ required: true, message: "请选择审批结果", trigger: "change" }],
  comment: [{ required: true, message: "请输入审批意见", trigger: "blur" }],
});
const bookingApprovalFormRef = ref();

// 打开预约审批弹框
function openBookingAuditDialog(row: any) {
  currentBookingRow.value = row;
  bookingAuditDialogVisible.value = true;
  bookingApprovalForm.value = {
    id: row.id,
    approverUserCode: userInfo.userCode || "",
    approvalRecordId: row.applicationId,
    flowId: row.flowId,
    result: "",
    comment: "",
  };

  // 更新审批流程步骤
  getAuditProgress(row.flowId);
}

// 提交预约审批
function submitBookingApproval() {
  if (bookingApprovalLoading.value) return;
  bookingApprovalFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      bookingApprovalLoading.value = true;
      submitAPI({
        approverUserCode: bookingApprovalForm.value.approverUserCode || "",
        approvalRecordId: bookingApprovalForm.value.id || "",
        flowId: bookingApprovalForm.value.flowId || "",
        result: bookingApprovalForm.value.result,
        comment: bookingApprovalForm.value.comment,
      })
        .then(() => {
          ElMessage.success("预约审批提交成功");
          bookingAuditDialogVisible.value = false;
          // 刷新列表
          getEquipmentList();
        })
        .catch(() => {
          ElMessage.error("预约审批提交失败");
        })
        .finally(() => {
          bookingApprovalLoading.value = false;
        });
    }
  });
}

// 打开设备详情
function openEquipmentDetail(row: any) {
  const route = router.resolve({
    path: "/equipment/details-look",
    query: {
      id: row?.deviceDetail?.id,
    },
  });
  console.log(route);
  window.open(route.href, "_blank");
}
</script>

<style scoped lang="scss">
#EquipmentBookingAuditPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    padding-top: 1rem;
    padding-left: 1rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    .item-label {
      display: inline;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: right;
      color: $text-color-regular;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn {
    position: absolute;
    right: 3.2rem;
    top: 1rem;
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    margin-top: 1rem;
    padding-left: 1rem;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .signal-status.IDLE {
    color: #999;
  }
  .signal-status.RESERVEING {
    color: $color_warning;
  }
  .signal-status.IN_USE {
    color: $color_success;
  }
  .signal-status.REPAIRING {
    color: $color_danger;
  }
  .signal-status.DAMAGED {
    color: $color_danger;
  }
  .signal-status.SCRAPPED {
    color: $color_danger;
  }

  .equipment-name-wrapper {
    display: flex;
    align-items: center;
    .equipment-photo {
      width: 5rem;
      height: 5rem;
      border-radius: 0.5rem;
      margin-right: 1rem;
    }
    .equipment-info-wrapper {
      display: flex;
      flex-direction: column;
      .equipment-name {
        padding-top: 0.5rem;
        font-size: $font-size-base;
      }
      .equipment-sn {
        font-size: $font-size-tips;
        color: $text-color-secondary;
      }
    }
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}

// 审批进度样式
.audit-progress-container {
  .progress-steps {
    .progress-step {
      display: flex;
      align-items: flex-start;
      position: relative;
      padding-bottom: 2rem;

      &:last-child {
        padding-bottom: 0;
      }

      .step-indicator {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 1rem;
        padding-top: 0.6rem;

        .step-circle {
          width: 1rem;
          height: 1rem;
          border-radius: 50%;
          border: 2px solid $border-color-primary;
          background-color: #fff;
          z-index: 2;
        }

        .step-line {
          position: absolute;
          top: 0.6rem;
          bottom: 0;
          width: 1px;
          background-color: $border-color-primary;
        }
      }

      .step-content {
        flex: 1;
        padding-top: 0.125rem;

        .step-title {
          font-size: $font-size-base;
          font-weight: 500;
          color: $text-color-regular;
          margin-bottom: 0.25rem;
        }
        .step-time {
          font-size: $font-size-tips;
          color: $text-color-secondary;
          margin-bottom: 0.25rem;
        }

        .step-handler {
          font-size: $font-size-tips;
          color: $text-color-secondary;
        }
      }

      // 已完成状态
      &.COMPLETED {
        .step-indicator {
          .step-circle {
            background-color: #52c41a;
            border-color: #52c41a;
          }
          .step-line {
            background-color: #52c41a;
          }
        }
        .step-content .step-title {
          color: #52c41a;
        }
      }

      // 进行中状态
      &.IN_PROGRESS {
        .step-indicator {
          .step-circle {
            background-color: #1890ff;
            border-color: #1890ff;
          }
          .step-line {
            background-color: #d9d9d9;
          }
        }
        .step-content .step-title {
          color: #1890ff;
        }
      }

      // 待处理状态
      &.NOT_STARTED {
        .step-indicator {
          .step-circle {
            background-color: #fff;
            border-color: #d9d9d9;
          }
          .step-line {
            background-color: #d9d9d9;
          }
        }
        .step-content .step-title {
          color: #999;
        }
      }
    }
  }
}

// 申请设备
.handle-message {
  margin-bottom: 2rem;
  padding-left: 3rem;
  font-size: $font-size-page-menu;
  color: $color_brand;
}

// 申请审批弹框样式
.apply-audit-container {
  .apply-info-section,
  .approval-process-section,
  .approval-comment-section {
    margin-bottom: 2rem;

    .section-title {
      font-size: $font-size-block-title;
      font-weight: 500;
      color: $text-color-regular;
      margin-bottom: 1rem;
      padding-bottom: 0.5rem;
      border-bottom: 1px solid $border-color-primary;
    }
  }

  .apply-info-content {
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 0.75rem;

      .info-label {
        width: 10rem;
        color: $text-color-secondary;
        font-size: $font-size-base;
        text-align: right;
      }

      .info-value {
        color: $text-color-regular;
        font-size: $font-size-base;
      }

      .detail-link {
        margin-left: 0.5rem;
        color: $color_brand;
        cursor: pointer;
        font-size: $font-size-base;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }

  .process-steps {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    position: relative;
    padding: 1rem 0;

    .process-step {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      flex: 1;

      .step-circle {
        width: 1.5rem;
        height: 1.5rem;
        border-radius: 50%;
        border: 2px solid #d9d9d9;
        background-color: #fff;
        margin-bottom: 0.5rem;
        z-index: 2;
        position: relative;
      }

      .step-line {
        position: absolute;
        top: 0.75rem;
        left: 50%;
        width: 100%;
        height: 2px;
        background-color: #d9d9d9;
        z-index: 1;
      }

      .step-content {
        text-align: center;

        .step-title {
          font-size: $font-size-base;
          color: $text-color-regular;
          margin-bottom: 0.25rem;
        }

        .step-time {
          font-size: $font-size-base;
          color: $text-color-secondary;
          margin-bottom: 0.25rem;
        }

        .step-status {
          font-size: $font-size-base;
        }
      }

      // 已完成状态
      &.COMPLETED {
        .step-indicator {
          .step-circle {
            background-color: #52c41a;
            border-color: #52c41a;
          }
          .step-line {
            background-color: #52c41a;
          }
        }
        .step-content .step-title {
          color: #52c41a;
        }
      }

      // 进行中状态
      &.IN_PROGRESS {
        .step-indicator {
          .step-circle {
            background-color: #1890ff;
            border-color: #1890ff;
          }
          .step-line {
            background-color: #d9d9d9;
          }
        }
        .step-content .step-title {
          color: #1890ff;
        }
      }

      // 待处理状态
      &.NOT_STARTED {
        .step-indicator {
          .step-circle {
            background-color: #fff;
            border-color: #d9d9d9;
          }
          .step-line {
            background-color: #d9d9d9;
          }
        }
        .step-content .step-title {
          color: #999;
        }
      }
    }
  }
}
</style>
